import json
import pyautogui
import time
import os
import binFile
import datetime
import openocd
import GetPort

class Bank:
    def __init__(self):
        self.addressStart = None
        self.addressEnd = None

class Main:
    def __init__(self):
        self.xpxh_y = None
        self.bbh_y = None
        self.name = None
        self.log_value_list = None
        self.name = None
        self.allname = None
        self.add = None
        self.length = None
        self.XPXH = None
        self.BBH = None
        self.way = None
        self.jtag = None
        self.password = None
        self.xpxh_y = None
        self.bbh_y = None
        self.file = None
        self.app = openocd.Openocd()
        self.gpt = GetPort.GetPort()
        self.bank = Bank
        self.openocdBinName = None
        self.hexBinName = None
        self.fileName = None
        self.download_name = None
        self.CompareFile = None


    # 点击图片
    def choose(self,url):
        time.sleep(1)
        folder_window_position = pyautogui.locateOnScreen(url)
        if folder_window_position is None:
            print(url+ "无法找到文件夹窗口")
            self.choose(url)
        folder_window_center = pyautogui.center(folder_window_position)
        pyautogui.moveTo(folder_window_center, duration=1)
        pyautogui.click()

    # 找到图片
    def find(self,url):
        folder_window_position = pyautogui.locateOnScreen(url)
        if folder_window_position is None:
            print(url+ "无法找到文件夹窗口")
            self.find(url)
        folder_window_center = pyautogui.center(folder_window_position)
        return folder_window_center

    # 选择芯片和型号
    def caozuo(self):
        xinpxh = self.find("./image/XPXH.png")
        pyautogui.click(x=xinpxh.x + 50, y=xinpxh.y)
        time.sleep(1)
        pyautogui.click(x=xinpxh.x + 50, y=xinpxh.y + self.xpxh_y)
        time.sleep(1)
        banbenhao = self.find("./image/BBH.png")
        pyautogui.click(x=banbenhao.x + 50, y=banbenhao.y)
        time.sleep(1)
        pyautogui.click(x=banbenhao.x + 50, y=banbenhao.y + self.bbh_y)
        time.sleep(1)
        ljfs = self.find("./image/LJFS.png")
        pyautogui.click(x=ljfs.x + 50, y=ljfs.y)
        time.sleep(1)
        pyautogui.click(y=ljfs.y + 20)
        time.sleep(1)
        time.sleep(1)
        refresh = self.find("./image/refresh.png")
        pyautogui.click(refresh)

    def choosefile(self):
        self.choose('./image/chooseFile.png')
        time.sleep(1)
        # 点击文件路径
        locat = self.find("./image/open.png")
        pyautogui.click(x=locat.x + 60, y=locat.y + 15)
        time.sleep(1)
        # 写文件路径
        pyautogui.typewrite(f"D:\hx_downloader_tool\downloader\case\{self.name}")
        time.sleep(1)
        # 之后回车
        pyautogui.press('enter')
        # 点击文件名输入框
        self.choose('./image/name.png')
        # 输入文件名
        pyautogui.typewrite(self.fileName)
        # 选择打开
        self.choose('./image/openfile.png')
        time.sleep(1)
        pyautogui.press('enter')
        time.sleep(20)


        # 生成bin文件并对比
    def readfile(self):
        time.sleep(2)
        isConnect = Main.app.connect(self.XPXH, self.BBH, self.password)
        if isConnect == False:
            print("连接失败")
            Main.app.setEvent()
            thread.join(1)
            time.sleep(1)
            # Main.readfile()
            return

        time.sleep(1)
        isOK = True
        for i in range(len(self.bank)):
            self.app.send(f'{self.allname} unlock 0')
            time.sleep(1)
            self.file = f'./case/{self.name}/' + self.fileName
            self.CompareFilePath = f'./case/{self.name}/' + self.CompareFile
            print(self.file)
            if self.allname == "hxs320f28034_cdd" or self.allname == "hxm32g407_cdd":
                self.app.send("riscv.cpu riscv set_mem_access sysbus")
                time.sleep(1)
                self.app.send("mww 0x7af890 0x5")
                time.sleep(1)

            self.app.send(f'dump_image {self.openocdBinName}bank{i}.bin 0x{str(self.bank[i].get("addressStart"))} {self.length}')
            print(f'dump_image {self.openocdBinName}bank{i}.bin 0x{str(self.bank[i].get("addressStart"))} {self.length}')
            time.sleep(30)
            os.system(f'java -cp com.haawking.core_1.1.7.jar HexToBin {self.CompareFilePath} {self.hexBinName}bank{i}.bin {str(self.bank[i].get("addressStart"))} {str(self.bank[i].get("addressEnd"))}')
            print(f'java -cp com.haawking.core_1.1.7.jar HexToBin {self.CompareFilePath} {self.hexBinName}bank{i}.bin {str(self.bank[i].get("addressStart"))} {str(self.bank[i].get("addressEnd"))}')
            time.sleep(5)

            hexToBin = binFile.GetFileMd5(f'{self.hexBinName}bank{i}.bin')
            openocdToBin = binFile.GetFileMd5(f'{self.openocdBinName}bank{i}.bin')
            if (hexToBin == openocdToBin):
                result = "Success"
                if isOK:
                    isOK = True
            else:
                result = "Failure"
                isOK = False
                # 将数据存放到result.txt文件
            with open("result_end.txt", "a") as f:
                f.write(
                    f'{self.allname},{result},{self.download_name},HexToBin:{hexToBin},openocd:{openocdToBin},{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")} "\n')
        with open("result_zuhe.txt", "a") as f:
            f.write(f'{self.allname}, {self.download_name},bin文件对比结果为: {isOK},{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")} "\n')
        self.app.setEvent()
        self.app.close()


    def logFile(self):
        log_path = "D:/Desktop/1.2.14.0.3/haawking_downloader_1.2.14.0.3Beta9/log.log"
        # 文件下载完成
        i = 1
        # 打开日志文件
        time.sleep(2)
        with open(log_path, 'r') as log_path_file:
            while (i):
                content = log_path_file.read()
                for log_item in self.log_value_list:
                    if log_item in content:
                        time.sleep(0.5)
                        pyautogui.press('enter')
                        i = 0
                        print(log_item)
                        break
        time.sleep(2)




    def json(self):
        main_data = json.load(open('main.json', 'r', encoding='utf-8'))
        image_data = json.load(open('image.json', 'r', encoding='utf-8'))
        # json里第一个choose: [1 2 3 4]
        for main_item in main_data:
            choose_list = main_item.get("choose")
            Main.download_name = main_item.get("name")
            Main.log_value_list = main_item.get("run_value")

            Main.fileName = main_item.get('downloaderFile')
            Main.CompareFile = main_item.get('CompareFile')
            print(Main.fileName)

            Main.openocdBinName = "D:/hx_downloader_tool/downloader/binfile/openocd_bin/" + Main.fileName
            Main.hexBinName = "D:/hx_downloader_tool/downloader/binfile/HexToBin/" + Main.fileName
            Main.caozuo()
            Main.choosefile()

            # 遍历choose里的每个内容
            for choose_item in choose_list:
                # 遍历image.json文件
                for image_item in image_data:
                    # 通过key找到图片地址
                    if image_item.get('key') == choose_item:
                        Main.choose(image_item.get('path'))
                        print(image_item.get('path'))
                        # time.sleep(1)
            Main.choose('./image/Perform.png')

            # 对比log日志
            Main.logFile()
            Main.readfile()

    def jsonfile(self):
        data = json.load(open('test_1.2.14.0.3.json', 'r', encoding='utf-8'))
        # self.name = str(input("请输入芯片型号：")).upper()
        for item in data:
            print(item)
            # if self.name == item.get("name"):
            Main.name = item.get("name")
            Main.allname = item.get("allname")
            Main.add = item.get("add")
            Main.bank = item.get("bank")
            Main.length = item.get("length")
            Main.XPXH = item.get("XPXH")
            Main.BBH = item.get("BBH")
            Main.way = item.get("way")
            Main.jtag = item.get("jtag")
            Main.password = item.get("password")
            Main.xpxh_y = item.get("xpxh_y")
            Main.bbh_y = item.get("bbh_y")
            # downloader.gpt.jtag_port(comName,downloader.jtag)

            time.sleep(1)
            Main.json()

if __name__ == "__main__":
    Main = Main()
    Main.jsonfile()

